package com.example.day04.controller.union;

import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.co.ProcessJoinFunction;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

public class IntervalJoinWith {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<Tuple2<String, Integer>> ds1 = env
                .socketTextStream("node3", 7777)
                .map(new MapFunction<String, Tuple2<String, Integer>>() {
                    @Override
                    public Tuple2<String, Integer> map(String value) throws Exception {
                        String[] datas = value.split(",");
                        return Tuple2.of(datas[0], Integer.parseInt(datas[1]));
                    }
                })
                // 数据流可能存在少量的无序事件，但是你可以保证这些事件的无序程度不会超过某个时间范围时，就可以使用这种方法来生成水印。这样可以帮助你在处理数据时，更准确地界定事件窗口，避免因为数据无序而导致窗口处理逻辑出错
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple2<String, Integer>>forBoundedOutOfOrderness(Duration.ofSeconds(3)) // 使用单调递增的时间戳策略生成水印。这适用于数据流中时间戳总是递增的情况。
                                .withTimestampAssigner((value, ts) -> value.f1 * 1000L)); // 指定如何根据元素的值来分配时间戳。

        SingleOutputStreamOperator<Tuple3<String, Integer, Integer>> ds2 = env
                .socketTextStream("node3", 8888)
                .map(new MapFunction<String, Tuple3<String, Integer,Integer>>() {
                    @Override
                    public Tuple3<String, Integer, Integer> map(String value) throws Exception {
                        String[] datas = value.split(",");
                        return Tuple3.of(datas[0], Integer.parseInt(datas[1]), Integer.parseInt(datas[2]));
                    }
                }).assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Tuple3<String, Integer, Integer>>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.f1 * 1000L));


        OutputTag<Tuple2<String, Integer>> leftLateTag = new OutputTag<>("left-late", Types.TUPLE(Types.STRING, Types.INT));
        OutputTag<Tuple3<String, Integer, Integer>> rightLateTag = new OutputTag<>("right-late", Types.TUPLE(Types.STRING, Types.INT, Types.INT));

//        1、只支持事件时间
//        2、指定上界、下界的偏移，负号代表时间往前，正号代表时间往后
//        3、process中，只能处理 join上的数据
//        4、两条流关联后的watermark，以两条流中最小的为准
//        5、如果 当前数据的事件时间 < 当前的watermark，就是迟到数据，主流的process不处理 */
        SingleOutputStreamOperator<String> processor = ds1.keyBy(value -> value.f0).intervalJoin(ds2.keyBy(value -> value.f0)).between(Time.seconds(-2), Time.seconds(2)).sideOutputLeftLateData(leftLateTag).sideOutputRightLateData(rightLateTag).process(new ProcessJoinFunction<Tuple2<String, Integer>, Tuple3<String, Integer, Integer>, String>() {
            @Override
            public void processElement(Tuple2<String, Integer> left, Tuple3<String, Integer, Integer> right, ProcessJoinFunction<Tuple2<String, Integer>, Tuple3<String, Integer, Integer>, String>.Context ctx, Collector<String> out) throws Exception {
//                ctx.output(leftLateTag, left);
//                ctx.output(rightLateTag, right);
                out.collect(left + "===" + right);
            }
        });
        processor.getSideOutput(leftLateTag).print();
        processor.getSideOutput(rightLateTag).print();
        processor.print();
        env.execute("zhao");
    }
}
